package com.mmall.common;

import com.mmall.annotation.RequsetPremission;
import com.mmall.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * http的url请求前后监听工具
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
    //http请求前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*log.info("--------------------------------------拦截当前的方法：{}--------------------------------------",(HandlerMethod) handler);
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            RequsetPremission premission =handlerMethod.getMethod().getAnnotation(RequsetPremission.class);
            System.err.println("打印：名字："+premission.permissionName()+"--url:"+premission.url()+"--状态："+premission.state());
        }*/
        //可以在这里定义拦截前的处理方法
        String url = request.getRequestURL().toString();
        Map map = request.getParameterMap();
        log.info("响应开始：url{},params:{}",url, JsonMapper.objToString(map));
        return true;//处理成功返回true
    }

    //http请求后执行
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        /*String url = request.getRequestURL().toString();
        Map map = request.getParameterMap();
        log.info("post响应之后：url{},params:{}",url, JsonMapper.objToString(map));*/
        removeThreadLocalInfo();
    }

    //http请求后执行
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url = request.getRequestURL().toString();
        Map map = request.getParameterMap();
        log.info("响应以后：url{},params:{}",url, JsonMapper.objToString(map));
        removeThreadLocalInfo();
    }

    /**
     * 移除已处理的进程内容
     */
    public void removeThreadLocalInfo(){
        log.info("销毁H：RequestHolder");
        RequestHolder.remove();
    }
}
